#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
 

int main(int argc, char **argv)
{
    const char *projectDir = "/home/radek/projekty";
    const char *projectName = "testyZlecenia";
    const char *devDir = "dev";
    const char *permFile = "rkperms_data";

    int u,g,o;
    uid_t user;
    gid_t group;
 
    char filesInfo[4][1024]; 

    char path[1024];

    struct stat fileStat;
  
    strcpy(path, "");
    strcat(path, projectDir);
    strcat(path, "/");
    strcat(path, projectName);
    strcat(path, "/");
    strcat(path, devDir);
    strcat(path, "/");
    strcat(path, permFile);

    //printf("%s", path);

    char * pch;
    int t1;
    FILE *file = fopen (path, "r" );  
    if ( file != NULL ) {
		char line [1024]; 
		while ( fgets ( line, sizeof(line), file ) != NULL ) {
		    t1 = 0; 
		    pch = strtok (line, ";\n");
		    while (pch != NULL) {
			   strcpy(filesInfo[t1++], pch); /* record 0mode, 1u, 2g, 3path2file*/
//                        printf ("%s\n", pch);
			   pch = strtok (NULL, ";\n");
		    }
            
		//   printf("-- %s %s %s %s\n", filesInfo[0], filesInfo[1], filesInfo[2], filesInfo[3]);	

		   if (lstat(filesInfo[3], &fileStat) < 0) {
			perror(filesInfo[3]);
		   } else {
			   /* files permissions evaluation, numeric format */
			    u=0;
			    if (fileStat.st_mode & S_IRUSR) 
				u+=4;
			    if (fileStat.st_mode & S_IWUSR)
				u+=2;
			    if (fileStat.st_mode & S_IXUSR) 
				u+=1;
		
			    g=0;
			    if (fileStat.st_mode & S_IRGRP)
				g+=4;
			    if (fileStat.st_mode & S_IWGRP)
				g+=2;
			    if (fileStat.st_mode & S_IXGRP)
				g+=1;

			    o=0;	
			    if (fileStat.st_mode & S_IROTH)
				o+=4;
			    if (fileStat.st_mode & S_IWOTH)
				o+=2;
			    if (fileStat.st_mode & S_IXOTH)
				o+=1;


			    int was_change = 0;
			    int mod_saved = (int)strtol(filesInfo[0], NULL, 8);
//				printf("%o --> %s\n", mod_saved, filesInfo[0]);
			    int mod_new = 100 * u + 10 * g + o;
				
			    char msg[1024], t1_msg[1024];
	                  sprintf(msg ,"%s: changed: %d %d %d -> %o %s %s", filesInfo[3], mod_new, fileStat.st_uid, fileStat.st_gid,
									mod_saved, filesInfo[1], filesInfo[2]);	

			    if (atoi(filesInfo[0]) != mod_new) {
									 
					if (!chmod(filesInfo[3], mod_saved)) {
						was_change = 1;
					} else {
						was_change = 2; /* meaning error */
						perror("Can't change permissions !!!");
					}
			    }


			    if  (was_change == 1) {
				printf("%s\n", msg);
			    }

			    //printf("%d", 100 * u + 10 * g + o);
			    //printf(" %d", fileStat.st_uid);
			    //printf(" %d\n", fileStat.st_gid);

			    
	          }


		}
		fclose (file);
    } else {
		perror (path);
    }


    return 0;
}
